//
//  JCMessage.swift
//  JChat
//
//  Created by JIGUANG on 10/04/2017.
//  Copyright © 2017 HXHG. All rights reserved.
//

import UIKit
import JMessage


/// 自定义消息类型
/* 消息体结构
    giftnotify = {"messageType":"giftnotify", "giftInfo":["msgId":100,"status":0-1-2]}
    0 - normal, 1 - 已领取, 2 - 已过期
 */
enum CustomMessageType : String {
    case unknow = "unknow"
    case gift = "gift" /// 礼物消息
    case redpack = "redpack" /// 红包消息
    case pullNotify = "pullnotify" /// 红包领取提示
    case activity = "activity" /// 俱乐部活动消息
    case task = "task"/// 聚会任务消息
    case partytaskEnd = "partytask" /// 聚会任务结束
    case giftnotify = "giftnotify" /// 用户同意好友申请后发送的礼物接收消息
    case pullGift = "pullGift" /// 用户手动领取别人发送的礼物
}

open class JCMessage: NSObject, JCMessageType {

    init(content: JCMessageContentType) {
        self.content = content
        self.options = JCMessageOptions(with: content)
        super.init()
    }
    
    public let identifier: UUID = .init()
    open var msgId = ""
    open var name: String = "UserName"
    open var date: Date = .init()
    open var sender: JMSGUser?
    open var senderAvator: UIImage?
    open var receiver: JMSGUser?
    open var content: JCMessageContentType
    public let options: JCMessageOptions
    open var updateSizeIfNeeded: Bool = false
    open var unreadCount: Int = 0
    open var targetType: MessageTargetType = .single
    open var contentType: JMSGContentType = .text
    open var jmessage: JMSGMessage?
}

extension JMSGMessage {
    typealias Callback = (JMSGMessage, Data?) -> Void
    func parseMessage(_ delegate: JCMessageDelegate, _ updateMediaMessage: Callback? = nil) -> JCMessage {
        var msg: JCMessage!
        let currentUser = JMSGUser.myInfo()
        let isCurrent = fromUser.isEqual(to: currentUser)
        let state = self.ex.state

        switch(contentType) {
        case .text:
            if ex.isBusinessCard {
                let businessCardContent = JCBusinessCardContent()
                businessCardContent.delegate = delegate
                businessCardContent.appKey = ex.businessCardAppKey
                businessCardContent.userName = ex.businessCardName
                msg = JCMessage(content: businessCardContent)
            } else {
                let content = self.content as! JMSGTextContent
                msg = JCMessage(content: JCMessageTextContent(text: content.text))
            }
        case .image:
            let content = self.content as! JMSGImageContent
            let imageContent = JCMessageImageContent()
            imageContent.imageSize = content.imageSize
            if ex.isLargeEmoticon {
                imageContent.imageSize = CGSize(width: 80, height: 80)
            }
            if state == .sending {
                content.uploadHandler = {  (percent:Float, msgId:(String?)) -> Void in
                    imageContent.upload?(percent)
                }
            }
            imageContent.delegate = delegate
            msg = JCMessage(content: imageContent)
            msg.options.showsBubble = false
            if let path = content.thumbImageLocalPath {
                let image = UIImage(contentsOfFile: path)
                imageContent.image = image
                msg.content = imageContent
            } else {
                content.thumbImageData({ (data, id, error) in
                    if let data = data {
                        if let updateMediaMessage = updateMediaMessage {
                            updateMediaMessage(self, data)
                        }
                    }
                })
            }
        case .eventNotification:
            let content = self.content as! JMSGEventContent
            let noticeContent = JCMessageNoticeContent(text: content.showEventNotification())
            msg = JCMessage(content: noticeContent)
            msg.options.showsTips = false
        case .voice:
            let content = self.content as! JMSGVoiceContent
            let voiceContent = JCMessageVoiceContent()
            voiceContent.duration = TimeInterval(content.duration.intValue)
            voiceContent.delegate = delegate
            msg = JCMessage(content: voiceContent)
            content.voiceData({ (data, id, error) in
                if let data = data {
                    voiceContent.data = data
                }
            })
        case .video:
            printLog("video message")
            let content = self.content as! JMSGVideoContent
            let videoContent = JCMessageVideoContent()
            videoContent.delegate = delegate
            msg = JCMessage(content: videoContent)
            
            if state == .sending {
                content.uploadHandler = {  (percent:Float, msgId:(String?)) -> Void in
                    videoContent.uploadVideo?(percent)
                }
            }
            
            if let path = content.videoThumbImageLocalPath {
                let url = URL(fileURLWithPath: path)
                let thumbData = try! Data(contentsOf: url)
                videoContent.image = UIImage(data: thumbData)
            }else{
                content.videoThumbImageData { (data, id, error) in
                    if let data = data {
                        if let updateMediaMessage = updateMediaMessage {
                            updateMediaMessage(self, data)
                        }
                    }
                }
            }
            videoContent.videoContent = content;
        case .file:
            printLog("file message")
            let content = self.content as! JMSGFileContent
            if ex.isShortVideo {
                let videoContent = JCMessageVideoContent()
                videoContent.delegate = delegate
                videoContent.videoFileContent = content;
                msg = JCMessage(content: videoContent)
            } else {
                let fileContent = JCMessageFileContent()
                fileContent.delegate = delegate
                fileContent.fileName = content.fileName
                fileContent.fileType = ex.fileType
                fileContent.fileSize = ex.fileSize
                if let path = content.originMediaLocalPath {
                    let url = URL(fileURLWithPath: path)
                    fileContent.data = try! Data(contentsOf: url)
                }
                msg = JCMessage(content: fileContent)
            }
        case .location:
            let content = self.content as! JMSGLocationContent
            let locationContent = JCMessageLocationContent()
            locationContent.address = content.address
            locationContent.lat = content.latitude.doubleValue
            locationContent.lon = content.longitude.doubleValue
            locationContent.delegate = delegate
            msg = JCMessage(content: locationContent)
        case .prompt:
            let content = self.content as! JMSGPromptContent
            let noticeContent = JCMessageNoticeContent(text: content.promptText)
            msg = JCMessage(content: noticeContent)
            msg.options.showsTips = false
        case .custom:
            let content: JMSGCustomContent = self.content as! JMSGCustomContent
            switch content.customMsgType() {
            case .gift:
                if let dict : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                    let noticeContent = JCMessageGiftContent(dict)
                    noticeContent.delegate = delegate
                    msg = JCMessage(content: noticeContent)
                } else {
                    msg = JCMessage(content: JCMessageNoticeContent.unsupport)
                }
            case .redpack:
                
                if let dict : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                    let noticeContent = JCRedPackContent(dict)
                    noticeContent.delegate = delegate
                    msg = JCMessage(content: noticeContent)
                } else {
                    msg = JCMessage(content: JCMessageNoticeContent.unsupport)
                }
            case .pullNotify:
                if let dict : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                    let noticeContent = JCRedPackTipContent(dict)
                    noticeContent.delegate = delegate
                    msg = JCMessage(content: noticeContent)
                } else {
                    msg = JCMessage(content: JCMessageNoticeContent.unsupport)
                }
            case .activity:
                if let dict : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                    let noticeContent = JCClubActivityContent(dict)
                    noticeContent.delegate = delegate
                    msg = JCMessage(content: noticeContent)
                } else {
                    msg = JCMessage(content: JCMessageNoticeContent.unsupport)
                }
            case .task:
                if let dict : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                    let noticeContent = JCMessageTaskContent(dict)
                    noticeContent.delegate = delegate
                    msg = JCMessage(content: noticeContent)
                } else {
                    msg = JCMessage(content: JCMessageNoticeContent.unsupport)
                }
            case .partytaskEnd:
                if let dict : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                    let noticeContent = JCMessageEndPartyContent(dict)
                    noticeContent.delegate = delegate
                    msg = JCMessage(content: noticeContent)
                } else {
                    msg = JCMessage(content: JCMessageNoticeContent.unsupport)
                }
            case .giftnotify:
                if let dict : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                    let noticeContent = JCMessageGiftNotiyContent(dict)
                    noticeContent.delegate = delegate
                    msg = JCMessage(content: noticeContent)
                } else {
                    msg = JCMessage(content: JCMessageNoticeContent.unsupport)
                }
            case .pullGift:
                if let dict : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                    let noticeContent = JCMessagePullGiftNotiyContent(dict)
                    noticeContent.delegate = delegate
                    msg = JCMessage(content: noticeContent)
                } else {
                    msg = JCMessage(content: JCMessageNoticeContent.unsupport)
                }
            default:
                msg = JCMessage(content: JCMessageNoticeContent.unsupport)
                break
            }
//            // 消息类型 type 1 - 红包
//            let key = "type"
//            if let type: String = dict[key] as? String {
//                switch type {
//                    case "1":
//                        let noticeContent = JCRedPackContent()
//                        msg = JCMessage(content: noticeContent)
//                        break
//                    default: break
//                }
//                break
//            }
            
        default:
            msg = JCMessage(content: JCMessageNoticeContent.unsupport)
        }
        if msg.options.alignment != .center {
           msg.options.alignment = isCurrent ? .right : .left
//           if self.targetType == .group {
           msg.options.showsCard = false
//           }
        }
        msg.targetType = MessageTargetType(rawValue: self.targetType.rawValue)!
        msg.msgId = self.msgId
        msg.options.state = state
        if isCurrent {
            msg.senderAvator = UIImage.getMyAvator()
        }
        msg.sender = fromUser
        msg.name = fromUser.displayName()
        msg.unreadCount = getUnreadCount()
        msg.contentType = contentType
        msg.jmessage = self
        return msg
    }
}

